<?php
/**
 * Created by PhpStorm.
 * User: 曹旺
 * Date: 2018-03-16
 * Time: 09:41
 */

namespace app\index\model;

use think\Db;
use think\Model;

class Order extends Model
{

    /**
     * @param $user_id
     * @return array|false|mixed|\PDOStatement|string|Model
     * 收货地址
     * @author  曹旺
     * @data  10:39
     */
    public function generate_order_address($user_id, $address_id)
    {
        //return 111;
        if (!isset($address_id)) {
            //return 123;
            $result = Db::table('nbsm_user_address')->field('id,consignee,consignee_phone,address_info,address')
                ->where('state=1 and sort=1 and user_id = ' . $user_id)->find();
            if (!empty($result)) {
                $result_last = $result;
            } else {
                $results = Db::table('nbsm_user_address')->field('id,consignee,consignee_phone,address_info,address')
                    ->where('state=1 and sort=0 and user_id = ' . $user_id)->find();
                if (!empty($results)) {
                    $result_last = $results;
                } else {
                    $result_last = null;
                }
            }
        } else {
            //return 321;
            //$address=Db::table('nbsm_user_address')->field('id')->where(['user_id'=>$user_id])->select();
            $result = Db::table('nbsm_user_address')->field('id,consignee,consignee_phone,address_info,address')
                ->where(['state' => 1, 'id' => $address_id,'user_id'=>$user_id])->find();
            //return $result;
            $result_last = $result;
        }

        return $result_last;
    }

    /**
     * @param $data [id:商品id,'number':购买数量]
     * @return mixed
     * 购物车添加到订单前的商品信息
     * @author  曹旺
     * @data  16:59
     */
    public function generate_order_info($data, $result_last,$user_discount_rate)
    {
        //一个订单不同商品所需的运费及详情
        //$commodity='';
        if (!empty($result_last)) {
            //return $data;
            foreach ($data as $key => $value) {
                $commodity[$key] = Db::table('nbsm_commodity')->field('id,commodity_name,commodity_unit,commodity_now_price,express_way,commodity_free_shipping,weight,commodity_address,commodity_url')
                    ->where(['id' => $value['id']])->find();
                $commodity[$key]['commodity_now_price']=round($commodity[$key]['commodity_now_price']*$user_discount_rate,2);
                //return $commodity;
                if ($commodity[$key]['commodity_address'] != '') {
                    /*
                      $address=json_decode($commodity[$key]['commodity_address'],true);
                    //return $address;
                    $count=count($address);
                    for ($i=0;$i<$count;$i++){
                        //return $address[$i]['province'];
                        if ($address[$i]['province']==$result_last['address']){
                            $commodity[$key]['commodity_address']='当前省份不在配送范围';
                            continue;
                        }else{
                            $commodity[$key]['commodity_address']='当前省份在配送范围';
                        }
                    }*/
                    //return 1;
                    $address = json_decode($commodity[$key]['commodity_address'], true);
                    //return $address;
                    foreach ($address as $k => $v) {
                        if ($v['province'] == $result_last['address']) {
                            //不配送省份
                            //return $v['province'];
                            //return 1111;
                            $commodity[$key]['commodity_address'] = '0';
                            break;
                        } else {
                            //配送省份
                            //return $v['province'];
                            //return $result_last['address'].'+';
                            $commodity[$key]['commodity_address'] = '1';
                        }
                    }
                    //return $commodity[$key]['commodity_address'];
                }
                if ($commodity[$key]['commodity_free_shipping'] == 1) {
                    //return 2;
                    $pay = [["pay_way" => "包邮"]];
                    $commodity[$key]['express_way'] = $pay;
                    $commodity[$key]['express_way_price'] = 0;
                } else {
                    //return 3;
                    $commodity[$key]['express_way'] = json_decode($commodity[$key]['express_way'], true);
                        //省份id
                        $province_id = Db::table('nbsm_pay_address')->field('id')->where(['province' => $result_last['address']])->find();
                        //商品的重量
                        //return $province_id;
                        $weight = ($value['number'] * $commodity[$key]['weight']);
                        //return $weight;
                        foreach ($commodity[$key]['express_way'] as $k => $v) {
                            //运费
                            //return $commodity[$key]['express_way'];
                            if ($v['pay_way'] == '冷链') {
                                $datas['within_min'] = array('lt', $weight);
                                $datas['within_max'] = array('egt', $weight);
                                $datas['province_id'] = $province_id['id'];
                                $price = Db::table('nbsm_pay_price_lenglian')->field('price')
                                    ->where($datas)->find();
                                //return $price['price'].'+'.$weight;
                                $commodity[$key]['express_way_price'] = $price['price'];
                                //return $commodity[$key]['express_way_price'];
                            } else {
                                $datas['within_min'] = array('lt', $weight);
                                $datas['within_max'] = array('egt', $weight);
                                $datas['province_id'] = $province_id['id'];
                                $price = Db::table('nbsm_pay_price_lenglian')->field('price')
                                    ->where($datas)->find();
                                //return $price['price'].'-'.$weight;
                                $commodity[$key]['express_way_price'] = $price['price'];
                            }
                            //return $price['price'].'='.$weight;
                        }
                }
                $commodity[$key]['number'] = $value['number'];
                //return $commodity[$key];
            }
            //return $commodity;
            $freights = 0;
            $commodity_amounts = 0;
            foreach ($commodity as $ka => $va) {
                //return $commodity;
                $pay_wayss='';
                //运费
                if ($va['commodity_address'] == 1) {
                    //return 321;
                    //return $commodity[$ka]['commodity_address'];
                    $freight = $va['express_way_price'];
                    $commodity_amount = $va['commodity_now_price'] * $va['number'];
                    /*return $va['express_way'][0]['pay_way'];
                    $pay_way=json_decode($va['express_way']);
                    return  $pay_way;*/
                    $commodity_amounts = $commodity_amounts + $commodity_amount;
                    $freights = $freights + $freight;
                    foreach ($va['express_way'] as $vaa=>$vaaa){
                        $pay_way[]=$vaaa['pay_way'];
                        //return $pay_way;
                    }
                    $pay_ways=array_values($pay_way);
                    $pay_wayss=array_values(array_unique($pay_ways));

                }else{
                    //return 123;
                    $pay_wayss=['配送不到'];
                    $commodity_amounts = $commodity_amounts;
                    $freights = $freights;

                }

            }
            //return $freights + $commodity_amounts;
            return $commodity_info = ['pay_way'=>$pay_wayss,'freight' => $freights, 'commodity_amounts' => $commodity_amounts, 'total' => $freights + $commodity_amounts, 'consignee_address' => $result_last, 'commodity' => $commodity];
        } else {
            //return 5;
            $commodity_amounts=0;
            foreach ($data as $key => $value) {
                $commodity[$key] = Db::table('nbsm_commodity')->field('id,commodity_name,commodity_unit,commodity_now_price,express_way,commodity_free_shipping,weight,commodity_address,commodity_url')
                    ->where(['id' => $value['id']])->find();
                $commodity[$key]['commodity_now_price']=round($commodity[$key]['commodity_now_price']*$user_discount_rate,2);
                /*if ($commodity[$key]['commodity_free_shipping'] == 1) {
                    $pay = [["pay_way" => "包邮"]];
                    $commodity[$key]['express_way'] = $pay;
                    $commodity[$key]['express_way_price'] = 0;
                } else {
                    $commodity[$key]['express_way'] = json_decode($commodity[$key]['express_way'], true);
                    if ($result_last != '') {
                        //省份id
                        $province_id = Db::table('nbsm_pay_address')->field('id')->where(['province' => $result_last['address']])->find();
                        //商品的重量
                        //return $province_id;
                        $weight = ($value['number'] * $commodity[$key]['weight']);
                        //return $weight;
                        foreach ($commodity[$key]['express_way'] as $k => $v) {
                            //运费
                            //return $commodity[$key]['express_way'];
                            if ($v['pay_way'] == '冷链') {
                                $datas['within_min'] = array('lt', $weight);
                                $datas['within_max'] = array('egt', $weight);
                                $datas['province_id'] = $province_id['id'];
                                $price = Db::table('nbsm_pay_price_lenglian')->field('price')
                                    ->where($datas)->find();
                                //return $price;
                                $commodity[$key]['express_way_price'] = $price['price'];
                                //return $commodity[$key]['express_way_price'];
                            } else {
                                $datas['within_min'] = array('lt', $weight);
                                $datas['within_max'] = array('egt', $weight);
                                $datas['province_id'] = $province_id['id'];
                                $price = Db::table('nbsm_pay_price_suyun')->field('price')
                                    ->where($datas)->find();
                                //return $price;
                                $commodity[$key]['express_way_price'] = $price['price'];
                            }
                        }
                    } else {
                        $commodity[$key]['express_way_price'] = '?';
                    }
                }*/
                $commodity[$key]['number'] = $value['number'];
            }
            foreach ($commodity as $ka => $va) {
                $commodity_amount = $va['commodity_now_price'] * $va['number'];
                $commodity_amounts = $commodity_amounts + $commodity_amount;
            }
            return $commodity_info = ['pay_way'=>'','freight' => 0, 'commodity_amounts' => $commodity_amounts, 'total' =>$commodity_amounts, 'consignee_address' => $result_last, 'commodity' => $commodity];
        }

        //return $commodity_info;
    }

    /**
     * @param $user_id
     * @return array|false|mixed|\PDOStatement|string|Model
     * 取用户的收货地址
     * @author  曹旺
     * @data  15:49
     */
    public function userorder_address($user_id)
    {
        $result = Db::table('nbsm_user_address')->field('consignee,consignee_phone,address_info')
            ->where('state=1 and sort=1 and user_id = ' . $user_id)->find();
        return $result;
    }

    /**
     * @param $arr
     * 用户id、订单状态
     * @return false|mixed|\PDOStatement|string|\think\Collection
     * 取订单相关数据
     * @author  曹旺
     * @data  09:12
     */
    public function user_order($arr)
    {
        $res = Db::table('nbsm_order')->field('id,order_number,money,order_state')->where($arr)
            ->where('state_del=1')->order('id desc')->select();
        foreach ($res as $key => $value) {
            $res_child = Db::table('nbsm_order_commodity')->field('commodity_id as id,commodity_url as url,money,commodity_name,number,commodity_unit,commodity_now_price')
                ->where('order_id=' . $value['id'] . ' and state=1')->select();
            $res[$key]['commodity'] = $res_child;
        }
        return $res;
    }

    /**
     * @param $data [order_number订单编号,money订单金额,user_id用户id]
     * @return int|string
     *  生成（确认）订单
     * @author  曹旺
     * @data  13:16
     */
    public function make_order($data)
    {
        $order_id = Db::table('nbsm_order')->insertGetId($data);
        return $order_id;
    }

    /**
     * @param $commodity
     * @return array
     * 验证商品库存
     * @author  曹旺
     * @data  10:33
     */
    public function rand_commodity_number($commodity)
    {
        foreach ($commodity as $k => $v) {
            $commodity_number = Db::table('nbsm_commodity')->field('commodity_number')->where(['id' => $v['id']])
                ->find();
            if ($commodity_number['commodity_number'] >= $v['number']) {
                $state['state'] = 1;
                $state['id'] = $v['id'];
                $state['commodity_number'] = $commodity_number['commodity_number'];
            } else {
                $state['state'] = 0;
                $state['id'] = $v['id'];
                $state['commodity_number'] = $commodity_number['commodity_number'];
            }
            $states[] = $state;
        }
        return $states;
    }

    /**
     * @param $commodity
     * @return array
     * 修改商品库存
     * @author  曹旺
     * @data  10:33
     */
    public function commodity_number($commodity)
    {
        $i = 0;
        foreach ($commodity as $k => $v) {
            $commodity_number = Db::table('nbsm_commodity')->field('id,commodity_number')->where(['id' => $v['id']])
                ->find();
            if ($commodity_number['commodity_number'] >= $v['number']) {
                $commodity_number_new['commodity_number'] = $commodity_number['commodity_number'] - $v['number'];
                $commodity_number_new['id'] = $commodity_number['id'];
                Db::table('nbsm_commodity')->update($commodity_number_new);
                $i++;
            } else {
                return 0;
            }
        }
        return $i;
    }

    /**
     * @param $commodity
     * @param $order_id
     * @return int
     * 添加订单商品信息
     * @author  曹旺
     * @data  10:34
     */
    public function make_order_commodity($commodity, $order_id,$user_discount_rate)
    {
        //return $commodity[0]['id'];
        $num = 0;
        foreach ($commodity as $key => $value) {
            $commodity_info = Db::table('nbsm_commodity')->field('id as commodity_id,commodity_code,commodity_name,commodity_title,commodity_describe,
            commodity_class,commodity_group,commodity_parameter,commodity_now_price,commodity_original_price,commodity_free_shipping
            ,express_way,preferential_promotion,commodity_details,commodity_key,weight,commodity_url,commodity_unit')->where(['id'=>$value['id']])->find();
            //return $commodity_info;
            $commodity_info['commodity_now_price']=round($commodity_info['commodity_now_price']*$user_discount_rate,2);
            $commodity_info['number'] = $value['number'];
            $commodity_info['money'] = $value['number'] * $commodity_info['commodity_now_price'];
            $commodity_info['weight'] = $value['number'] * $commodity_info['weight'];
            $commodity_info['order_id'] = $order_id;
            $res = Db::table('nbsm_order_commodity')->insert($commodity_info);
            $num += $res;
        }
        if ($num == count($commodity)) {
            return 1;
        } else {
            return 0;
        }
    }

    /**
     * @param $id订单id
     * @return false|int|string
     * 修改订单状态（取消订单）
     * @author  曹旺
     * @data  10:40
     */
    public function order_cancel($id)
    {
        $result = Db::table('nbsm_order')->where(['id' => $id])->update(['state_del' => 0]);
        if ($result){
            $commodity=Db::table('nbsm_order_commodity')->field('commodity_id,number')->where(['order_id'=>$id])->select();
            foreach ($commodity as $key=>$value){
                $commodity_num=Db::table('nbsm_commodity')->field('commodity_number')->where(['id'=>$value['commodity_id']])->find();
                $num=$commodity_num['commodity_number']+$value['number'];
                //return $num;
                Db::table('nbsm_commodity')->where(['id'=>$value['commodity_id']])->update(['commodity_number'=>$num]);
            }
            return true;
        }
        return false;
    }

    /**
     * @param $id订单id
     * @return false|int|string
     * 修改订单状态为4
     * @author  曹旺
     * @data  11:01
     */
    public function order_receipt($id)
    {
        $result = Db::table('nbsm_order')->where(['id' => $id])->update(['order_state' => 4]);
        return $result;
    }


    /**
     * @param $order_id
     * @param $user_id
     * @return array|false|mixed|\PDOStatement|string|Model
     * 获取订单是否支付状态
     * @author  曹旺
     * @data  16:10
     */
    public function order_state($order_id,$user_id){
        $res=Db::table('nbsm_order')->field('order_state')->where(['id'=>$order_id,'user_id'=>$user_id])->find();
        return $res;
    }
}